package util;
/*
数据库工具类
 */

import java.io.IOException;
import java.io.InputStream;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.SQLException;
import java.util.Properties;

public class DBUtil {
    private static String driver;
    private static String url;
    private static String username;
    private static String password;

    static {
        //1.读取配置文件
        InputStream is = DBUtil.class.getClassLoader().
                getResourceAsStream("jdbc.properties");
        //2.创建处理 properties 文件对象
        Properties properties = new Properties();
        try {
            //3.properties 对象读取配置文件
            properties.load(is);
            //4.获取配置文件中指定的值
            driver = properties.getProperty("driver");
            url = properties.getProperty("url");
            username = properties.getProperty("username");
            password = properties.getProperty("password");
            //5.加载驱动类
            Class.forName(driver);

        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

    //获取连接
    public static Connection getConnection() {
        Connection connection = null;
        try {

            connection = DriverManager.getConnection(url, username, password);

        } catch (SQLException e) {
            e.printStackTrace();
        }
        return connection;
    }

    //关闭资源
    public static void closeAll(AutoCloseable... closeabless) {
        for (AutoCloseable closeable : closeabless) {
            if (closeable != null) {
                try {
                    closeable.close();
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        }
    }
}
